#include "apue.h"
#define BSZ 48

int main() {
    char buf[BSZ];
    FILE *fp;

    // 1. 用字符a改写缓冲区
    memset(buf, 'a', BSZ - 2);
    buf[BSZ - 1] = '\0';
    buf[BSZ - 2] = 'X';

    // 2. fmeopen在缓冲区处放置null字节
    if ((fp = fmemopen(buf, BSZ, "w+")) == NULL) {
        err_sys("fmemopen failed");
    }
    printf("initial buffer contents: %s\n", buf);
    fprintf(fp, "hello, world");
    printf("before fflush: %s\n", buf);

    // 3. fflush刷新缓冲区
    fflush(fp);

    // null字节加到了字符串尾部
    printf("after fflush: %s\n", buf);
    printf("len of strin in buf = %ld\n", (long) strlen(buf));

    // 4. 用字符b改写缓冲区
    memset(buf, 'b', BSZ - 2);
    buf[BSZ - 1] = '\0';
    buf[BSZ - 2] = 'X';
    fprintf(fp, "hello, world");

    // 5. fseek重定位流上的文件指针
    /*
     int fseek( FILE *stream, long offset, int origin);
        1. stream，文件指针
        2. offset，正数为正向偏移量，负数为反向偏移量
        3. origin：
             SEEK_SET： 文件开头
             SEEK_CUR： 当前位置
             SEEK_END： 文件结尾
     */
    fseek(fp, 0, SEEK_CUR);

    printf("after fseek:%s\n", buf);
    printf("len of string in buf = %ld\n", (long) strlen(buf));

    // 6. 用字符c改写缓冲区
    memset(buf, 'c', BSZ - 2);
    buf[BSZ - 1] = '\0';
    buf[BSZ - 2] = 'X';
    fprintf(fp, "hello, world");

    // 7. 关闭流
    fclose(fp);

    // 没有追加写入null字节
    printf("after fclose: %s\n", buf);
    printf("len of string in buf = %ld\n", (long) strlen(buf));
    return 0;
}